package net.pimpas.web.jsf.renderers.ajax.validate.html;

import java.io.IOException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseId;

import net.pimpas.web.jsf.components.ajax.UIAjax;
import net.pimpas.web.jsf.components.ajax.populate.UIAjaxPopulate;
import net.pimpas.web.jsf.components.ajax.validate.UIAjaxValidate;
import net.pimpas.web.jsf.renderers.RendererBase;
import net.pimpas.web.jsf.util.AjaxUtils;
import net.pimpas.web.jsf.util.ComponentUtils;

public class HtmlAjaxValidateRenderer extends RendererBase {
	
	@SuppressWarnings("unchecked")
	@Override
	public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
		if(!component.isRendered()) return;
		if(!ComponentUtils.isCorrectComponentType(component, UIAjaxValidate.class)) return;
		
		super.initResourceManager(context, component);
		
		UIAjaxValidate validate = (UIAjaxValidate) component;
		
		/*
		// look for message
		List components = ComponentUtils.getAllComponentsByClass(context.getViewRoot(), UIMessage.class);
		UIMessage message = null;
		for(Iterator<UIMessage> it = components.iterator();it.hasNext();message=null) {
			message = it.next();
			if(message.getFor().equals(parent.getId()))
				break;
		}
		
		if(message == null)
			throw new RuntimeException("[AJAXVALIDATE]: Cannot render component, Reason: Message for component with ID ["+parent.getId()+"] not found!");
		*/
		String controlId = null;
		if(validate.getControl() != null) {
			UIComponent control = ComponentUtils.getComponentById(context.getViewRoot(), context, validate.getControl(), ComponentUtils.SERVER_ID);
			if(control != null) controlId = "'"+control.getClientId(context)+"'";
		}
		
		
		AjaxUtils.attachAjaxEvent(validate, 
				"pimpas.AJAX.Populate.ProcessAJAX.execute(this, "+validate.getAsync().booleanValue()+", "+validate.getImmediate().booleanValue()+", " + validate.getSendForm().booleanValue()+
				", "+controlId+", [{name: '"+component.getClientId(context)+"', value: ''}," +
				"{name: '"+UIAjax.AJAX_OBJECT_REQUEST_KEY+"', value: '"+component.getClientId(context)+"'}]);",
				"AJAX_VALIDATE_KEY_CHECK");
	}
	
	
	@Override
	public void decode(FacesContext context, UIComponent component) {
		if(!component.isRendered()) return;
		if(!ComponentUtils.isCorrectComponentType(component, UIAjaxPopulate.class)) return;
		UIAjaxPopulate populate = (UIAjaxPopulate) component;
		if(populate.getActionListener() != null) {
			ActionEvent evt = new ActionEvent(component);
			evt.setPhaseId(PhaseId.INVOKE_APPLICATION);
			component.queueEvent(evt);
		}
	}
}